package com.sg.business.model.sap;

import java.sql.Connection;

import com.mobnut.commons.util.Utils;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.sg.business.model.etl.ISaleDataCollector;
import com.sg.sqldb.DDB;
import com.sg.sqldb.utility.IRowCallBack;
import com.sg.sqldb.utility.SQLRow;
import com.sg.sqldb.utility.SQLUtil;

public class SAPSaleDataCollector implements ISaleDataCollector {

	@Override
	public void runGetData(final DBCollection saleDataCol, int year, int month)
			throws Exception {
		IRowCallBack callback = new IRowCallBack() {

			@Override
			public void input(SQLRow row) {
				BasicDBObject dbo = new BasicDBObject();
				for (int i = 0; i < row.getColumns().length; i++) {
					Object v = row.getValue(row.getColumns()[i]);
					Object value = Utils.getJSONValueFromSQL(v);
					dbo.put(row.getColumns()[i], value);
				}
				saleDataCol.insert(dbo);
			}
		};
		String gjahr = "" + year; //$NON-NLS-1$
		String perde = String.format("%03d", month); //$NON-NLS-1$
		Connection connection = DDB.getDefault().createConnection("sap"); //$NON-NLS-1$
		try {
			SQLUtil.SQL_QUERY(
					"sap", //$NON-NLS-1$
					"select PALEDGER,GJAHR,PERDE ,MATNR ,VV010,VV030,VV040,BUKRS,BZIRK,KNDNR,VKBUR,VKGRP,VKORG " //$NON-NLS-1$
							+ "From SAPSR3.CE14000 " //$NON-NLS-1$
							+ "WHERE MANDT = '700' and PALEDGER = '02' and GJAHR = '" //$NON-NLS-1$
							+ gjahr + "' and PERDE = " + perde + "", callback, //$NON-NLS-1$ //$NON-NLS-2$
					connection);
		} catch (Exception e) {
		} finally {
			connection.close();
		}
	}

}
